<template>
    <el-drawer
        :model-value="showDrawer"
        v-bind="$attrs"
        direction="rtl"
        custom-class="drawer-building"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <el-form ref="searchFormRef" :model="searchForm" inline class="pinmei-form">
            <el-form-item prop="premisesTypeList">
                <el-select v-model="searchForm.premisesTypeList" collapse-tags placeholder="请选择" multiple>
                    <template #prefix>物业类型</template>
                    <el-option v-for="(item, key) in propertyType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item prop="areaList">
                <el-select
                    v-model="searchForm.areaList"
                    placeholder="请选择区域"
                    multiple
                    collapse-tags
                    clearable
                    filterable
                >
                    <template #prefix>行政区域</template>
                    <el-option v-for="item in areaList" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item prop="premisesPriceList">
                <el-select v-model="searchForm.premisesPriceList" collapse-tags placeholder="请选择" multiple>
                    <template #prefix>平均售价</template>
                    <el-option v-for="(item, key) in housePriceType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item prop="premisesName">
                <el-input v-model="searchForm.premisesName" placeholder="请输入">
                    <template #prefix>楼盘名称</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="inTime">
                <el-date-picker
                    v-model="searchForm.inTime"
                    clearable
                    class="in-time"
                    type="daterange"
                    placeholder="选择日期"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="propertyPrice">
                <el-input
                    v-model="searchForm.propertyPrice"
                    v-limitNumber="{ min: 0, decimal: 2 }"
                    placeholder="请输入"
                >
                    <template #prefix>物业费</template>
                    <template #append>以上</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="premisesFloor">
                <el-input
                    v-model="searchForm.premisesFloor"
                    v-limitNumber="{ min: 0 }"
                    :controls="false"
                    placeholder="请输入"
                >
                    <template #prefix>楼层</template>
                    <template #append>以上</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="occupancyRate">
                <el-input v-model="searchForm.occupancyRate" v-limitNumber="{ min: 0, max: 100 }" placeholder="请输入">
                    <template #prefix>入住率</template>
                    <template #append>%以上</template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="searchFormRef.resetFields()">重置</el-button>
                <el-button type="primary" @click="getUnselectedData(searchForm)">查询未选楼盘</el-button>
                <el-button type="primary" @click="getSelectedData(searchForm)">查询已选楼盘</el-button>
            </el-form-item>
        </el-form>

        <section class="handler-area">
            <section class="table-contailer">
                <h5>未选楼盘列表</h5>
                <XcTable
                    border
                    :height="500"
                    is-selectable
                    :loading="unselectedTableLoading"
                    :columns="unselectedTableColumns"
                    :data="unselectedTableData"
                    @selection-change="handleSeletionChange"
                ></XcTable>
            </section>
            <section class="btn-group">
                <el-button
                    size="mini"
                    type="primary"
                    icon="arrow-right"
                    class="icon-button"
                    :disabled="!selectedIds.length"
                    :loading="addLoading"
                    @click="handleAddBuilding"
                ></el-button>
                <el-button
                    size="mini"
                    type="primary"
                    icon="arrow-left"
                    class="icon-button"
                    :disabled="!unselectedIds.length"
                    :loading="deleteLoading"
                    @click="handleDeleteBuilding"
                ></el-button>
            </section>
            <section class="table-contailer">
                <h5>已选楼盘列表</h5>
                <XcTable
                    border
                    :loading="selectedTableLoading"
                    is-selectable
                    :height="500"
                    :columns="selectedTableColumns"
                    :data="selectedTableData"
                    @selection-change="handleSelectedSeletionChange"
                ></XcTable>
            </section>
        </section>
    </el-drawer>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, reactive, onMounted, computed, effect } from 'vue';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';
import { getUnselected, getSelected, addBuilding, deleteBuilding, getPlanInfo } from '@/api/plan.ts';
import { propertyType, housePriceType } from '@/utils/config.ts';
import { getAreaFromRigions } from '@/utils/common.ts';
import { idItem, idsList } from '../programType.ts';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

const props = defineProps({
    showDrawer: {
        type: Boolean,
        default: false,
    },
});

const store = useStore();
const planId = computed(() => store.state.plan.planId);
const areaList = ref([]);
const regionList: any = computed(() => store.state.app.common.CommonList?.regionList);
const selectedTableData = ref([]);
const unselectedTableData = ref([]);
const emit = defineEmits<{ (e: 'update:showDrawer', flag: boolean): void; (e: 'refresh'): void }>();
const searchFormRef = ref(null);
const selectedIds = ref([]);
const unselectedIds = ref([]);
const deleteLoading = ref(false);
const addLoading = ref(false);
const unselectedTableLoading = ref(false);
const selectedTableLoading = ref(false);
const searchForm = reactive({
    areaList: [],
    inTime: null,

    occupancyRate: null,
    planId: null,
    premisesFloor: null,
    premisesName: null,
    premisesPriceList: [],
    premisesTypeList: [],
    propertyPrice: null,
});

const selectedTableColumns = [
    { label: '项目名称', key: 'name' },
    { label: '调度数', key: 'counts', prop: { sortable: true } },
    { label: '单元数', key: 'units', prop: { sortable: true } },
    { label: '点位数', key: 'machines', prop: { sortable: true } },
];
const unselectedTableColumns = [
    { label: '项目名称', key: 'name' },
    { label: '单元数', key: 'units', prop: { sortable: true } },
    { label: '点位数', key: 'machines', prop: { sortable: true } },
];
const deleted = computed(() => store.state.plan.deleted);
const handleGetPlan = async (id) => {
    const data = await getPlanInfo({ planId: planId.value, deleted: deleted.value }) || {};
    const city = data.city;
    areaList.value = getAreaFromRigions(regionList.value, city);
};
handleGetPlan();
const getUnselectedData = async (searchForm = {}) => {
    const params = {
        ...searchForm,
        inTime: searchForm.inTime ? searchForm.inTime.join('~') : null,
        planId: planId.value,
    };
    unselectedTableLoading.value = true;
    try {
        const data = (await getUnselected(params)) || [];
        unselectedTableData.value = data;
    } finally {
        unselectedTableLoading.value = false;
    }
};

const getSelectedData = async (searchForm = {}) => {
    const params = {
        ...searchForm,
        inTime: searchForm.inTime ? searchForm.inTime.join('~') : null,
        planId: planId.value,
    };
    selectedTableLoading.value = true;
    try {
        const data = await getSelected(params) || [];
        selectedTableData.value = data;
    } finally {
        selectedTableLoading.value = false;
    }
};
const handleSeletionChange = (selected: idsList) => {
    selectedIds.value = selected.map(({ id }: idItem) => id);
};
const handleSelectedSeletionChange = (selected: idsList) => {
    unselectedIds.value = selected.map(({ id }: idItem) => id);
};

const init = () => {
    getUnselectedData();
    getSelectedData();
};

const handleAddBuilding = async () => {
    const params = {
        planId: planId.value,
        premisesIdList: selectedIds.value,
    };
    if (selectedIds.value.length) {
        addLoading.value = true;
        try {
            await addBuilding(params);
        } finally {
            addLoading.value = false;
        }
        init();
        emit('refresh');
    } else {
        ElMessage.warning('请选择项目');
    }
};

const handleDeleteBuilding = async () => {
    const params = {
        planId: planId.value,
        premisesIdList: unselectedIds.value,
    };
    if (unselectedIds.value.length) {
        deleteLoading.value = true;
        try {
            await deleteBuilding(params);
        } finally {
            deleteLoading.value = false;
        }
        init();
        emit('refresh');
    } else {
        ElMessage.warning('请选择项目');
    }
};

effect(() => {
    if (props.showDrawer) {
        init();
    }
});

// 关闭楼盘图Drawer
const handleClose = () => {
    emit('update:showDrawer', !props.showDrawer);
};
</script>

<style lang="scss" scoped>
.handler-area {
    display: flex;
    align-items: center;
    .table-contailer {
        flex: 1;
        h5 {
            margin-bottom: 10px;
        }
    }
    .btn-group {
        margin: 28px 20px 0;
        .el-button {
            display: block;
            width: 34px;
            height: 34px;
            min-width: auto;
            padding: 0;
            & + .el-button {
                margin: 20px 0 0;
            }
        }
    }
}
</style>
